/**
 * 
 */
package edu.hawaii.webspider;

import static java.lang.System.out;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.SAXException;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import java.util.logging.Logger;
import java.util.logging.Level;


/**
 * @author kenglish
 *
 */
public class MostPopular extends WebAnalysisTool {

  private int pagesToVisit = 100;

  /**
   * Create a MostPopular object. 
   */
  public MostPopular() {
    super();
  }

  /**
   * Create an object with startUrl.
   * @param startUrl The starting url for the web crawl.
   */
  
  public MostPopular(String startUrl) {
    super(startUrl);
  }

  /**
   * Returns the true if the stop condition is met.
   * @return true if stop condition is met.
   */
   
  @Override
  protected boolean isStopCondition() {
    // TODO Auto-generated method stub
    return webResponses.size() >= this.pagesToVisit;
  }
  /**
   * Returns the most popular link.
   * @param count Number of pages to crawl.
   * @return value of most popular link.
   */
  
  public String getMostPopularLink(int count) {
    this.pagesToVisit = count;
    if (!isValidHostUrl(this.startUrl)) {
      return null;
    }
    
    WebRequest request = new GetMethodWebRequest(this.startUrl);
    WebResponse response;
    String mostPopularUrl = null;
    Map<String,Integer> linkCounts = new HashMap<String,Integer>();    
    try {
      response = webConversation.getResponse(request);
      this.populateWebResponses(response);    
      for (String url : webResponses.keySet()) {
         for (WebLink link : webResponses.get(url).getLinks() ) {
           String urlString = getUrlString(link);
           if (urlString != null && webResponses.containsKey(urlString) ) {
             if (linkCounts.containsKey(urlString)) {
               linkCounts.put(urlString,linkCounts.get(urlString) + 1);
             } 
             else {
               linkCounts.put(urlString,1);
             }
           }
         }
         
      }
    }
    
    catch (MalformedURLException e) {
      return null;
    }
    catch (IOException e) {
      return null;
    }
    catch (SAXException e) {
      return null;
    }
    
    
    int maxValue = 0;
    for (Map.Entry<String, Integer> url : linkCounts.entrySet()) {
      
      logger.info(url.getValue() + " links point to " + url.getKey());              
      if (url.getValue() > maxValue) {
        mostPopularUrl = url.getKey();
        maxValue = url.getValue();
      }
    }
    out.println("The most popular page discovered is: " + mostPopularUrl + " with " +  maxValue + 
                " pages that point to it." );      
    return mostPopularUrl;
  }
  
  /**
   * main method.
   * @param args Command line arguments.
   */
  public static void main(String[] args) {
    Logger.getLogger("edu.hawaii.webspider").setLevel(Level.INFO);        
    String url = "http://www.google.com";
    MostPopular example = new MostPopular(url);
    example.getMostPopularLink(100);
  }
}
